package com.alibaba.datax.plugin.writer.miniowriter.handler;

import com.alibaba.datax.common.exception.DataXException;
import com.alibaba.datax.common.plugin.RecordReceiver;
import com.alibaba.datax.common.plugin.TaskPluginCollector;
import com.alibaba.datax.common.util.Configuration;
import com.alibaba.datax.plugin.unstructuredstorage.writer.Constant;
import com.alibaba.datax.plugin.writer.miniowriter.Key;
import com.alibaba.datax.plugin.writer.miniowriter.MinioWriterErrorCode;

import java.io.*;
import java.util.Objects;

import static com.alibaba.datax.plugin.writer.miniowriter.SupportType.getType;

/**
 * @Author JDragon
 * @Date 2021.07.12 下午 2:19
 * @Email 1061917196@qq.com
 * @Des:
 */
public class WriterHandlerSelector {
    public static WriterHandler buildWriterHandler(Configuration configuration, TaskPluginCollector taskPluginCollector, RecordReceiver lineReceiver, OutputStream outputStream) {
        String encoding = configuration.getString(Key.ENCODING, Constant.DEFAULT_ENCODING);
        String fileName = configuration.getNecessaryValue(Key.FILE_NAME, MinioWriterErrorCode.REQUIRED_VALUE);
        String type = configuration.getNecessaryValue(Key.SUFFIX, MinioWriterErrorCode.REQUIRED_VALUE);
        type = type.toLowerCase();
        WriterHandler writerHandler;
        switch (getType(type)) {
            case XLXS:
                writerHandler = new ExcelWriterHandler(fileName, outputStream);
                break;
            case CSV:
            case TXT:
                try {
                    Writer writer = new BufferedWriter(new OutputStreamWriter(outputStream, encoding));
                    writerHandler = new CsvTxtWriterHandler(writer, type);
                    break;
                } catch (UnsupportedEncodingException e) {
                    throw DataXException.asDataXException(MinioWriterErrorCode.IO_ERROR, e);
                }
            default:
                throw DataXException.asDataXException(MinioWriterErrorCode.TYPE_ERROR, String.format("错误的文件后缀%s", type));
        }
        writerHandler.setConfiguration(configuration);
        writerHandler.setTaskPluginCollector(taskPluginCollector);
        writerHandler.setLineReceiver(lineReceiver);
        return writerHandler;
    }
}
